package com.andon.springboot.seed.api;

import com.alibaba.fastjson.annotation.JSONField;
import com.andon.springboot.seed.emum.ApiResponseCode;
import com.andon.springboot.seed.emum.ServiceExceptionEnum;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author: baiwenlong
 * created on: 2018/11/11 9:33 PM
 * description: 通用返回值
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResponseUtil<T> implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(ApiResponseUtil.class);
    @JSONField(ordinal = 1)
    private long ts;
    @JSONField(ordinal = 2)
    private int code;
    @JSONField(ordinal = 3)
    private String msg;
    @JSONField(ordinal = 4)
    private T data;


    private ApiResponseUtil(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private ApiResponseUtil(int code, String msg, Object data) {
        this.ts = System.currentTimeMillis();
        this.code = code;
        this.msg = msg;
        this.data = (T) data;
    }

    /**
     * 使之不在json序列化结果当中
     */
    @JSONField(serialize = false)
    public boolean isSuccess() {
        return this.code == ApiResponseCode.SUCCESS.getCode();
    }

    public int getCode() {
        return code;
    }

    public T getData() {
        return data;
    }

    public String getMsg() {
        return msg;
    }

    public long getTs() {
        return ts;
    }


    public static <T> ApiResponseUtil<T> createBySuccess() {
        return new ApiResponseUtil<T>(ApiResponseCode.SUCCESS.getCode(), ApiResponseCode.SUCCESS.getMessage(), "1000");
    }

    public static <T> ApiResponseUtil<T> createBySuccess(Object data) {
        return new ApiResponseUtil<T>(ApiResponseCode.SUCCESS.getCode(), ApiResponseCode.SUCCESS.getMessage(),  data);
    }

    public static <T> ApiResponseUtil<T> createByErrorCode(int errorCode, String errorMessage) {
        return new ApiResponseUtil<T>(errorCode, errorMessage,  StringUtils.EMPTY);
    }
    public static <T> ApiResponseUtil<T> createByErrorCode(ServiceExceptionEnum serviceExceptionEnum) {
        return new ApiResponseUtil<T>(serviceExceptionEnum.getCode(), serviceExceptionEnum.getMessage(), StringUtils.EMPTY);
    }


}
